<template>
  <div class="container">
    <el-row class="">
      <el-col :span="12" align="left">
        <el-input v-model="data.params.name" placeholder="标准名称" style="width: 300px; margin-right: 15px" clearable />

        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="12" align="right">
        <el-button class="unlock" @click="getUnlockBtn()" v-limit="'KJSL:ZDKJXM:JSBZXM:UNLOCK'">解锁</el-button>
        <el-button class="lock" @click="getLockBtn()" v-limit="'KJSL:ZDKJXM:JSBZXM:LOCK'">锁定</el-button>
        <el-button class="ordinary" @click="getExportBtn()"  v-limit="'KJSL:ZDKJXM:JSBZXM:EXPERT'">批量导出</el-button>
        <el-button type="danger" @click="handleDetect()" v-limit="'KJSL:ZDKJXM:JSBZXM:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'KJSL:ZDKJXM:JSBZXM:ADD'">新增</el-button>
      </el-col>
    </el-row>


    <div>
      <Table class="table_" :loading="data.loading" :tableArr="data.allTableData" :pagination="data.page"
        @selectItem="getCurrentList" :columns="data.columns" :total="data.page.total" @delectTable="delectIds">
        <template #operate="{ row }">
          <el-button size="small" class="ordinary" v-show="row.updateFlag" :key="row.id + 'bj'" :disabled="row.isLock == 1" v-limit="'KJSL:ZDKJXM:JSBZXM:EDIT'"
            @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" class="ordinary"  @click="handleDetail(row)">详情</el-button>
          <el-button size="small" v-if="row.status == '待确认'" type="primary" :key="row.id + 'qr'"  v-limit="'KJSL:ZDKJXM:JSBZXM:CONFIRM'"
            :disabled="row.isLock == 1" @click="handleConfirm(row)">确认</el-button>
        </template>
      </Table>

      <div class="example-pagination-block">
        <el-pagination :current-page="pagination.currentPage" :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 40, 50, 100]" background layout="prev, pager, next ,total,sizes,jumper"
          :total="data.page.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <el-dialog v-model="data.dialogVisible" width="60%" top="10vh" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header" v-loading="data.detail_data">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <Information ref="getAssociation" v-if="data.dialogVisible" @valueFlag="valueFlag"></Information>
            </el-tab-pane>
            <el-tab-pane label="主编单位" name="2">
              <Members v-if="activeName=='2'" :members="data.members" :membersFlag="data.membersFlag" @paramsChange="paramsChange"></Members>
            </el-tab-pane>
            <el-tab-pane label="参编单位" name="3">
              <Members v-if="activeName=='3'" :members="data.participatingUnits" :membersFlag="data.membersFlag"
                @paramsChange="participatingChange"></Members>
            </el-tab-pane>
            <el-tab-pane label="编写人员" name="4">
              <Write v-if="activeName=='4'" :membersFlag="data.writeFlag" @paramsChangeInMember="paramsChangeInMember"
                @paramsChangeOutMember="paramsChangeOutMember" :inMember="data.inMember" :outMember="data.outMember">
              </Write>
            </el-tab-pane>

            <el-tab-pane label="相关附件" name="5">
              <platformFiles :files="data.files" @filesParams="filesParams"  download="KJSL:ZDKJXM:JSBZXM:DOWNLOAD"  upload="KJSL:ZDKJXM:JSBZXM:UPLOAD" fileDelete="KJSL:ZDKJXM:JSBZXM:FILEDELETE"></platformFiles>
            </el-tab-pane>


             <el-tab-pane label="变更记录" name="6"  v-if="data.addFlag==1" >
              <Record :changeLogs="data.changeLogs" ></Record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">关闭</el-button>
          <el-button type="primary" @click="handleSave()">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="data.detailVisible" width="60%" top="10vh" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header" v-loading="data.detailVisible_data">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <Informationxq ref="getAssociation" v-if="data.detailVisible" @valueFlag="valueFlag"></Informationxq>
            </el-tab-pane>
            <el-tab-pane label="主编单位" name="2">
              <Membersxq :members="data.members" :membersFlag="data.membersFlag" @paramsChange="paramsChange"></Membersxq>
            </el-tab-pane>
            <el-tab-pane label="参编单位" name="3">
              <Membersxq :members="data.participatingUnits" :membersFlag="data.membersFlag"
                @paramsChange="participatingChange"></Membersxq>
            </el-tab-pane>
            <el-tab-pane label="编写人员" name="4">
              <Writexq :membersFlag="data.writeFlag" @paramsChangeInMember="paramsChangeInMember"
                @paramsChangeOutMember="paramsChangeOutMember" :inMember="data.inMember" :outMember="data.outMember">
              </Writexq>
            </el-tab-pane>

            <el-tab-pane label="相关附件" name="5">
              <platformFiles :files="data.files" @filesParams="filesParams"  download="KJSL:ZDKJXM:JSBZXM:DOWNLOAD"  upload="KJSL:ZDKJXM:JSBZXM:UPLOAD" fileDelete="KJSL:ZDKJXM:JSBZXM:FILEDELETE"></platformFiles>
            </el-tab-pane>


             <el-tab-pane label="变更记录" name="6"  v-if="data.addFlag==1" >
              <Record :changeLogs="data.changeLogs" ></Record>
            </el-tab-pane>

          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Record from '@/views/science/keyScienceProject/scienceNormlProject/record/record.vue';
import platformFiles from "@/views/science/components/platformFiles/platformFiles.vue"
import platformFilesxq from "@/views/science/components/platformFiles/platformFilesxq.vue"
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { Modals, tips } from '@/views/science/components/tips/tips'
import { reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { getAddkproject, getConfirmkproject, getDelectkproject, getDetailkproject, getExportkproject, getListkproject, getLockkproject, getUnlockkproject, getUpdatekproject } from '../../api/technicalNorms'
import Information from './information.vue'
import Informationxq from './informationxq.vue'
import Members from './members.vue'
import Membersxq from './membersxq.vue'
import tableData from './tableHeader.json'
import Write from './write.vue'
import Writexq from './writexq.vue'
import {getProjectsDetail} from "@/views/science/api/international";
import { ElMessage } from 'element-plus';

export default {
  name: 'technicalNorms',
  components: {
    SelectOption,
    Table,
    Information,
    Informationxq,
    Members,
    Membersxq,
    Write,
    Writexq,
    platformFiles,
    platformFilesxq,
    Record,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    const pagination = reactive({  //分页器信息
      pageSize: 10,
      currentPage: 1,
    })
    const data = reactive({
      writeFlag: false,
      addFlag: 0,
      changeLogs: [],
      operLog: [],
      unit: [],
      inMember: [],
      outMember: [],
      dialogVisible: false,
      recordShow: false,
      loading: false,
      detail_data:false,
      page: { page: 1, limit: 10, total: 0 },
      params: {
        name: '',
        levelName: '',
        level: '',
        normType: '',
        mainUnit: '',
        enterpriseRanking: '',
        current: 1,
        size: 10,
        id: '',
        levelId: '',
        classId: '',
      },
      selectedRows: [] as any,
      columns: tableData.platformTableHeader,
    // {
    //   "key": "classType",
    //     "width": 140,
    //     "label": "标准类别"
    // },
      ids: [],
      allTableData: [],
      files: [],
      flag: null,
      members: [],
      writers: [],
      participatingUnits: [],
      information: [],
      undertakeUnitId: '',
      undertakeUnit: '',
      membersFlag: false,
      detailVisible_loading:false,
      detailVisible: false,
    })
    //详情数据获取
    const detailVisibleData = async (id) => {
      data.detailVisible_loading = true
      let res = await getDetailkproject(id)
      if (res.data.success) {
        const arr = res.data.data.info
        store.commit('technicalNorms/getForm', { ...arr })
        data.information = res.data.data.info
        data.members = res.data.data.chiefUnits
        data.participatingUnits = res.data.data.participatingUnits
        data.files = res.data.data.files
        data.membersFlag = true
        data.writeFlag = true
        data.inMember = res.data.data.inMember
        data.outMember = res.data.data.outMember
        data.changeLogs = res.data.data.operLog
console.log(11111, data.changeLogs)
        data.undertakeUnitId = res.data.data.undertakeUnitId
        data.undertakeUnit = res.data.data.undertakeUnit

        data.addFlag = 1
        data.detailVisible_loading = false
      }else{
        data.detailVisible_loading = false
      }

    }
    const handleDetail = (row) => {
      detailVisibleData(row.id)
      data.detailVisible = true
      data.addFlag = 1
      store.commit('technicalNorms/getRowId', row.id)
    }

    const handleClose = () => {
      data.detailVisible = false
      data.recordShow = false;
      activeName.value = '1'
    }    // 搜索
    const search = () => {
      data.page.page = 1
      console.log(data.params)
      tableList()
    }
    // 字段不明确，后期对字段，接口进行修改
    const changeValue = (item) => data.params.levelName = item.id
    const changeValue1 = (item) => data.params.levelName = item.itemValue
    const changeValue2 = (item) => data.params.mainUnit = item.itemValue
    const changeValue3 = (item) => data.params.enterpriseRanking = item.itemValue

    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.selectedRows = currentList
    }
    const delectIds = (ids) => {
      data.ids = ids
    }

    //主页面表格初始化
    const tableList = async () => {
      data.loading = true;
      data.params.size = pagination.pageSize
      data.params.current = pagination.currentPage

      let res = await getListkproject(data.params)
      if (res.data.success) {
        let records = res.data.data
        records.records.map((item) => {
          if (item.status == 0) {
            item.status = "待确认"
          } else {
            item.status = "已确认"
          }
        })
        data.loading = false;
        data.allTableData = res.data.data.records
        data.page.total = records.total
      }else{
        data.loading = false;
      }
    }
    //解锁
    const getUnlockBtn = async () => {
      if (data.ids.length) {
        Modals('是否解锁选择内容', '提示', 'warning').then(async () => {
          let res = await getUnlockkproject(data.ids)
          if (res.data.success) {
            tips('解锁成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }

    }
    //锁定
    const getLockBtn = () => {
      if (data.ids.length) {
        let flag = true
        console.log(data.selectedRows, 'selectedRows')
        data.selectedRows.forEach((obj) => {
          if (obj.status == '待确认') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '请确认后再进行锁定',
            type: 'warning',
          })
          return
        }
        Modals('是否锁定选择内容', '提示', 'warning').then(async () => {
          let res = await getLockkproject(data.ids)
          console.log(data.ids);
          if (res.data.success) {
            tips('锁定成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }
    }
    //导出
    const getExportBtn = async () => {
      Modals('是否导出以选择内容或者全部内容', '提示', 'warning').then(async () => {
        await getExportkproject({
          name: data.params.name || '',
          levelId: data.params.levelId || '',
          classId: data.params.classId || '',
          ids: data.ids,
        })
      }).catch(() => {
        console.log("点击了取消")
      })
    }
    //批量删除
    const handleDetect = () => {
      if (data.ids) {
        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          let res = await getDelectkproject(data.ids)
          data.ids = []
          console.log(data.params, '啥啊啊啊啊删除');

          if (res.data.success) {
            tips('删除成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }

    }

    // 内部人员


    let paramsChangeInMember = (params) => {

      data.writeFlag = false;

      data.inMember = params
    }


    // 外部人员
    let paramsChangeOutMember = (params) => {

      data.writeFlag = false;

      data.outMember = params
    }

    //新增
    const handleAdd = () => {
      data.dialogVisible = true
      data.addFlag = 0
      data.members = []
      data.information = []
      data.participatingUnits = []
      data.inMember = []
      data.outMember = []
      data.files = []
      store.commit('technicalNorms/emptyForm')

    }
    //主编单位组件 传来的
    const paramsChange = (val) => {
      console.log('主编单位组件 传来的', val);
      data.membersFlag = false
      data.members = val
    }
    //参编单位组件 传来的
    const participatingChange = (val) => {
      console.log('参编单位组件 传来的', val);
      data.membersFlag = false
      data.participatingUnits = val
    }

    //编辑
    const handleEdit = (row) => {
      data.dialogVisible = true
      data.addFlag = 1
      store.commit('technicalNorms/getRowId', row.id)
      detailData(row.id)
    }
    //详情数据获取
    const detailData = async (id) => {
      data.detail_data = true
      data.dialogVisible = true

      let res = await getDetailkproject(id)
      if (res.data.success) {
        const arr = res.data.data.info
        store.commit('technicalNorms/getForm', { ...arr })
        data.information = res.data.data.info
        data.members = res.data.data.chiefUnits
        data.participatingUnits = res.data.data.participatingUnits
        data.files = res.data.data.files
        data.changeLogs = res.data.data.operLog
        console.log(222222222222, data.changeLogs)
        data.membersFlag = true
        data.writeFlag = true
        data.inMember = res.data.data.inMember
        data.outMember = res.data.data.outMember

        data.undertakeUnitId = res.data.data.undertakeUnitId
        data.undertakeUnit = res.data.data.undertakeUnit

        data.addFlag = 1
        data.detail_data = false
      }else{
        data.detail_data = false
      }
    }
    //编辑
    const handlhandleEditeAdd = () => {
      data.dialogVisible = true
      data.addFlag = 1

    }
    //查看
    const handleConfirm = (row) => {

      Modals("是否确认当前流程", "提示", "warning")
        .then(async () => {
          let res = await getConfirmkproject({ id: row.id });
          if (res.data.success) {
            tableList()
          }
        })
        .catch(() => { });


    }
    const dataChange = () => {

      detailData(store.state.technicalNorms.rowId)
    }
    const valueFlag = (flag) => {
      data.flag = flag
    }
    //分页操作
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      tableList()
    }

    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      tableList()
    }

    const getAssociation = ref()
    // 保存
    const handleSave = async () => {
      const form = store.state.technicalNorms.form

      form.projectChangerName = form.projectChanger//项目负责人手动输入 没有id
      form.effectDate = form.effectDate ? form.effectDate : null
      form.startDate = form.startDate ? form.startDate : null
      form.endDate = form.endDate ? form.endDate : null
      form.failureDate = form.failureDate ? form.failureDate : null

      // console.log('form;;;;;',form)
      getAssociation.value.submitForm()
      if (!data.flag) {
        return tips('请将基本信息补充完整', 'warning')
      }
      // let  inMember = []
      // let  outMember = []

      const params = {
        // baseInfo:form,
        // memberList: data.members,
        // fileList: data.files,
        projectList: data.participatingUnits,
        writerList: data.writers,

        info: form,
        chiefUnits: data.members,//主编单位
        participatingUnits: data.participatingUnits,//参编单位
        inMember: data.inMember, //内部人员
        outMember: data.outMember,
        changeLogs: data.operLog,
        files: data.files,
      }

      let res
      if (data.addFlag == 0) {
        res = await getAddkproject(params)
      } else {
        res = await getUpdatekproject(params)
      }
      if (res.data.success) {
        data.dialogVisible = false
        activeName.value = '1'
        tableList()
      }

    }
    // 关闭
    const handleCloseDialog = () => {
      data.dialogVisible = false;
      data.recordShow = false;
      activeName.value = '1'
    }
    //上传附件
    const filesParams = (params) => {
      data.files = params
    }
    tableList()

    return {
      store,
      activeName,
      data,
      tableList,
      getCurrentList,
      delectIds,
      changeValue,
      changeValue1,
      changeValue2,
      changeValue3,
      search,
      getUnlockBtn,
      getLockBtn,
      getExportBtn,
      handleDetect,
      handleAdd,
      handleEdit,
      handlhandleEditeAdd,
      handleConfirm,
      handleCloseDialog,
      handleSave,
      dataChange,
      valueFlag,
      paramsChangeInMember,
      paramsChangeOutMember,
      getAssociation,
      pagination,
      handleSizeChange,
      handleCurrentChange,
      filesParams,
      paramsChange,
      participatingChange,
      handleDetail, //详情
      handleClose, //详情
    }
  }
}
</script>

<style lang="scss">
.table_ {
  .el-pagination {
    display: none;
  }
}
</style>

<style scoped lang="scss">
.container {
  background-color: white;
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: end;
}

:deep(.el-dialog__body) {
  display: none;
}

// 滚动条
:deep(.demo-tabs > .el-tabs__content) {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  -ms-overflow-style: none;
}
</style>
